<template>
  <div class="wrap">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- card -->
    <el-card class="box-card">
      <!-- 注意提示 -->
      <el-alert
        title="注意:只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
        :closable="false"
      />
      <!-- 商品分类 -->
      <div class="cate_row">
        <el-row>
          <el-col>
            <span class="cate_text">选择商品分类:</span>
            <!-- 级联选择器 -->
            <el-cascader
              v-model="selectCateValue"
              clearable
              :options="cateList"
              :props="cateOptions"
              style="widht:500px;"
              @change="handleChange"
            />
          </el-col>
        </el-row>
      </div>
      <!-- tabs切换-->
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many" :disabled="isDisabled">
          <el-button type="primary" :disabled="isDisabled" @click="addParams('many')">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table
            :data="paramsList"
            border
            max-height="520"
            style="width: 100%;margin-top:10px;"
          >
            <el-table-column
              width="50"
              type="expand"
            >
              <template slot-scope="scope">
                <el-tag
                  v-for="(tag,index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  :disable-transitions="false"
                  class="el_tag_class"
                  @close="handleClose(index,scope.row)"
                >
                  {{ tag }}
                </el-tag>
                <el-input
                  v-if="scope.row.inputVisible"
                  ref="saveTagInput"
                  v-model.trim="scope.row.inputValue"
                  class="input-new-tag"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                />
                <el-tag
                  v-else
                  type="success"
                  effect="plain"
                  style="cursor: pointer;margin-left: 5px;"
                  @click="showInput(scope.row)"
                >
                  + New Tag
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              type="index"
              label="#"
              width="50"
              align="center"
            />
            <el-table-column
              prop="attr_name"
              label="参数名称"
              align="center"
            />
            <el-table-column
              label="操作"
              align="center"
            >
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" @click="editParms(scope.row)">修改</el-button>
                <el-button type="danger" icon="el-icon-delete" @click="deleteParams(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only" :disabled="isDisabled">
          <el-button type="primary" :disabled="isDisabled" @click="addAttribute('only')">添加属性</el-button>
          <!-- 静态参数表格 -->
          <el-table
            :data="paramsList"
            border
            max-height="520"
            style="width: 100%;margin-top:10px;"
          >
            <el-table-column
              width="50"
              type="expand"
            >
              <template slot-scope="scope">
                <el-tag
                  v-for="(tag,index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  :disable-transitions="false"
                  class="el_tag_class"
                  @close="handleClose(index,scope.row)"
                >
                  {{ tag }}
                </el-tag>
                <el-input
                  v-if="scope.row.inputVisible"
                  ref="saveTagInput"
                  v-model.trim="scope.row.inputValue"
                  class="input-new-tag"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                />
                <el-tag
                  v-else
                  type="success"
                  effect="plain"
                  style="cursor: pointer;margin-left: 5px;"
                  @click="showInput(scope.row)"
                >
                  + New Tag
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              type="index"
              label="#"
              width="50"
              align="center"
            />
            <el-table-column
              prop="attr_name"
              label="参数名称"
              align="center"
            />
            <el-table-column
              label="操作"
              align="center"
            >
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" @click="editParms(scope.row)">修改</el-button>
                <el-button type="danger" icon="el-icon-delete" @click="deleteParams(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加参数弹出框 -->
      <el-dialog
        :title="changeAtrribute"
        :visible.sync="addParamsVisible"
        width="30%"
        @close="addParamsCancle()"
      >
        <el-form ref="addParamsRef" :model="addParamsForm" label-width="85px" :rules="addParamsRules">
          <el-form-item :label="activeName ==='many'?'动态参数:':'静态属性:'" prop="attr_name">
            <el-input v-model="addParamsForm.attr_name" />
          </el-form-item>
        </el-form>
        <!-- 表单底部 -->
        <div slot="footer" class="dialog-footer">
          <el-button @click="addParamsCancle">取 消</el-button>
          <el-button type="primary" @click="addParamsComfirm">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import { getGoodCateList } from '@/api/cate.js';
import { getParamsList, addAttributes, commitParams, getParams, deletParams, editParams } from '@/api/params.js';
export default {
  name: 'Params',
  components: { },
  data() {
    return {

      inputValue: '', // 输入框内的值
      // 添加参数校验规则
      addParamsRules: {
        attr_name: [
          { required: true, message: '请输入登录名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      },
      addParamsForm: {}, // 添加参数form
      addParamsVisible: false, // 添加参数弹出框是否可见
      activeName: 'many', // tabs选中的数据
      cateList: [], // 级联商品分类数据
      cateOptions: { // 商品分类配置项
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        expandTrigger: 'hover'
      },
      selectCateValue: [], // 选中的商品分类id
      paramsList: [], // 参数列表数据
      editParamsText: ''// 判断编辑或添加的标识
    };
  },
  computed: {
    // 参数按钮是否禁用
    isDisabled() {
      return !(this.selectCateValue.length > 0);
    },
    // 分类id
    cateId() {
      return this.selectCateValue.length != 3 ? null : this.selectCateValue[2];
    },
    changeAtrribute() {
      if (!this.editParamsText) {
        return this.activeName === 'many' ? '添加动态参数:' : '添加静态属性:';
      } else {
        return this.activeName === 'many' ? '修改动态参数:' : '修改静态属性:';
      }
    }
  },
  mounted() {
    this.getCateList();
  },
  methods: {
    // 编辑标签参数（删除、增加）
    getEditParams(row) {
      const params = {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(',')
      };
      editParams(this.cateId, row.attr_id, params).then((res) => {
        const { status, msg } = res.data.meta;
        if (status !== 200) return this.$message.error(msg);
        this.$message.success(msg);
      });
    },
    // 标签关闭时触发
    handleClose(index, row) {
      row.attr_vals.splice(index, 1);
      this.getEditParams(row);
    },
    // 点击输入框时触发
    showInput(row) {
      row.inputVisible = true;
      // 让文本框自动获得焦点
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    //  监听输入框（回车或焦点事件）
    handleInputConfirm(row) {
      const inputValue = row.inputValue;
      if (inputValue) {
        row.attr_vals.push(inputValue);
        this.getEditParams(row);
      }
      row.inputVisible = false;
      row.inputValue = '';
    },
    // 删除参数
    deleteParams(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletParams(this.cateId, row.attr_id).then((res) => {
          const { status, msg } = res.data.meta;
          if (status !== 200) return this.$message.error(msg);
          this.getParams();
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 修改参数
    editParms(row) {
      const params = {
        attr_name: this.addParamsForm.attr_name,
        attr_sel: this.activeName
      };
      this.editParamsText = row.attr_id;
      // 获取参数
      getParams(this.cateId, this.editParamsText, params).then((res) => {
        const { meta, data } = res.data;
        if (meta.status !== 200) return this.$message.error(meta.msg);
        this.addParamsForm = data;
        this.addParamsVisible = true;
      });
      //
    },
    // 添加参数
    addParams() {
      this.addParamsVisible = true;
    },
    // 添加属性
    addAttribute() {
      this.addParamsVisible = true;
    },
    // 添加参数或修改参数 确定
    addParamsComfirm() {
      this.$refs.addParamsRef.validate((valid) => {
        if (!valid) return false;
        const params = {
          attr_name: this.addParamsForm.attr_name,
          attr_sel: this.activeName
        };
        if (!this.editParamsText) {
          // 添加参数
          addAttributes(this.cateId, params).then((res) => {
            const { meta } = res.data;
            if (meta.status !== 201) return this.$message.error(meta.msg);
            this.$message.success(meta.msg);
            this.getParams();
            this.addParamsVisible = false;
          });
        } else {
          // 修改参数
          commitParams(this.cateId, this.editParamsText, params).then((res) => {
            const { meta } = res.data;
            if (meta.status !== 200) return this.$message.error(meta.msg);
            this.$message.success(meta.msg);
            this.getParams();
            this.addParamsVisible = false;
          });
        }
      });
    },
    // 添加参数 取消
    addParamsCancle() {
      this.addParamsVisible = false;
      this.editParamsText = '';
      this.$refs.addParamsRef.resetFields();
      this.addParamsForm = {};
    },
    // 获取参数列表
    getParams() {
      getParamsList(this.cateId, { sel: this.activeName }).then((res) => {
        const { data, meta } = res.data;
        if (meta.status !== 200) return this.$message.error(meta.msg);
        data.forEach(element => {
          // 控制文本框的输入和隐藏
          element.inputVisible = false;
          // 文本框中输入的值
          element.inputValue = '';
          element.attr_vals = element.attr_vals ? element.attr_vals.split(',') : [];
        });
        this.paramsList = data;
      });
    },
    // 监听tabs变化
    handleClick() {
      this.getParams();
    },
    /* 获取所有的商品分类数据列表 */
    getCateList() {
      getGoodCateList().then((res) => {
        const { data, meta } = res.data;
        if (meta.status !== 200) return this.$message.error(meta.msg);
        this.cateList = data;
      });
    },
    // 监听级联选择器
    handleChange(params) {
      if (params.length != 3) {
        this.selectCateValue = [];
        this.paramsList = [];
      } else {
        this.selectCateValue = params;
        this.getParams();
      }
    }
  }
};
</script>
<style scoped lang='scss'>
  .cate_row{
    margin:15px 0;
    .cate_text{
        font-size:17px;
        margin-right:8px;
    }
 }
.el_tag_class{
  margin:0 5px;
}
.button-new-tag {
    margin:0 5px;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
